package com.partner.service.login;

import java.util.ArrayList;  
import java.util.Collection;  
import java.util.Iterator;  
import java.util.List;  

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;  
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;  
import org.springframework.security.core.authority.SimpleGrantedAuthority;  
import org.springframework.security.core.userdetails.UserDetails;  
import org.springframework.security.core.userdetails.UserDetailsService;  
import org.springframework.security.core.userdetails.UsernameNotFoundException;  
import org.springframework.stereotype.Service;  

import com.partner.bean.login.UserDetail;
import com.partner.bean.sysright.TSysuser;
import com.partner.bean.sysright.TSysuserVo;
import com.partner.mapper.sysright.TSysrightMapper;
import com.partner.mapper.sysright.TSysuserMapper;
/**  
 * 该类是用户信息的定义和验证  
 * 这个类主要是处理用户登录信息，在用户输入用户名和密码后，  
 * spring security会带着用户名调用类里面的loadUserByUsername(usrename)方法，  
 * 通过用户名查出用户信息，然后把数据库中查出的用户密码和刚刚用户输入的存储在session中的密码做比较，然后判断该用户是否合法！   
 *  
 */  
@Service("customUserDetailsService")  
public class CustomUserDetailsService implements UserDetailsService {
	
	@Autowired
	private TSysuserMapper serviceMapper;
	@Autowired
	private TSysrightMapper  tsysrightMapper;

    @Override  
    public UserDetails loadUserByUsername(String userName)  
            throws UsernameNotFoundException, DataAccessException {
    	TSysuser ts = new TSysuser();
    	ts.setUsername(userName);
        //根据登录名获取登陆用户     
    	TSysuserVo user = serviceMapper.getSysUserbyUsername(ts);
        if(null == user) { 
        	//System.out.println("用户" + userName + "不存在");
             throw new UsernameNotFoundException("用户" + userName + "不存在");
        }
        //根据用户的 类型获取用户权限  
        if(user.getIsuse().equals("n")){ //禁用账号  
        	//System.out.println("用户" + userName + "被禁用");
        	throw new LockedException("用户" + userName + "被禁用");  
        }
        Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();           
        auths.add(new SimpleGrantedAuthority(user.getRoleid()+""));     
        boolean enabled = true;  
        boolean accountNonExpired = true;  
        boolean credentialsNonExpired = true;  
        boolean accountNonLocked = true;  
  
        UserDetail userdetail = new UserDetail(userName, user.getPassword(), enabled, accountNonExpired,  
                        credentialsNonExpired, accountNonLocked, auths);
        
        return userdetail; 
    }  
  
} 
